<?php

namespace Wenhsing;

use RuntimeException;

class Watermark
{
    protected $in = __DIR__ . DIRECTORY_SEPARATOR . 'imgs';

    protected $out = __DIR__ . DIRECTORY_SEPARATOR . 'out';

    // protected $extensions = [
    //     'jpg', 'jpeg',
    //     'png', 'gif',
    // ];

    private $files = [];

    public function __construct($config = [])
    {
        $this->setConfig($config);
    }

    public function setConfig($config) {
        foreach (['in', 'out'] as $v) {
            if (isset($config[$v])) {
                $this->$v = $config[$v];
            }
        }
        return $this;
    }

    public function run()
    {
        set_time_limit(0);
        $this->scan();

        foreach ($this->files as $k => $v) {
            $rsult = $this->addWatermark($v['origin'], $this->out . $v['dir'], $v['name']);
            echo (($rsult) ? '[success] ' : '[error]') . $v['name'] . PHP_EOL;
        }
    }

    public function scan($path = '')
    {
        $currPath = $this->in . DIRECTORY_SEPARATOR . $path;

        if (!is_dir($currPath)) {
            throw new RuntimeException("It's not a directory", 1);
        }
        $tmp = scandir($currPath);
        foreach ($tmp as $k => $v) {
            if ($v != '.' && $v != '..') {
                $uri = $path . DIRECTORY_SEPARATOR . $v;
                $fullPath = $this->in . $uri;
                if (is_dir($fullPath)) {
                    $this->scan($uri);
                }
                if (is_file($fullPath)) {
                    $this->files[] = [
                        'origin'    => $fullPath,
                        'name'      => $v,
                        'dir'       => $path,
                    ];
                }
            }
        }
    }

    public function addWatermark(string $path, string $savePath, string $saveName = '')
    {
        // 获取图片信息
        $info = @getimagesize($path);
        if (false === $info || IMAGETYPE_GIF === $info[2]) {
            return false;
        }
        // 获取图片后缀
        $type = image_type_to_extension($info[2], false);
        $fun      = "imagecreatefrom{$type}";
        $im = @$fun($path);


        // 获取水印图片信息
        $watermarkInfo = @getimagesize(__DIR__ . DIRECTORY_SEPARATOR . 'watermark.png');
        if (false === $watermarkInfo || IMAGETYPE_GIF === $watermarkInfo[2]) {
            return false;
        }
        // 获取图片后缀
        $watermarkType = image_type_to_extension($watermarkInfo[2], false);
        $watermarkFun      = "imagecreatefrom{$watermarkType}";
        $watermarkIm = @$watermarkFun(__DIR__ . DIRECTORY_SEPARATOR . 'watermark.png');


        list($w, $h) = $info;
        list($watermarkW, $watermarkH) = $watermarkInfo;
        $dst_w = $w / 8;
        $dst_h = $dst_w * $watermarkH / $watermarkW;
        $dst_x = $w - ($dst_w * 2);
        $dst_y = $h - ($dst_h * 2);

        // imagecopyresized($im, $watermarkIm, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $watermarkW, $watermarkH);
        imagecopyresampled($im, $watermarkIm, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $watermarkW, $watermarkH);


        if (!file_exists($savePath . DIRECTORY_SEPARATOR)) {
            mkdir($savePath . DIRECTORY_SEPARATOR, 0755, true);
        }
        $pathname = $savePath . DIRECTORY_SEPARATOR . $saveName;

        //保存图像
        if ('jpeg' == $type || 'jpg' == $type) {
            //JPEG图像设置隔行扫描
            imageinterlace($im, true);
            imagejpeg($im, $pathname, 80);
        } elseif ('png' == $type) {
            //设定保存完整的 alpha 通道信息
            imagesavealpha($im, true);
            //ImagePNG生成图像的质量范围从0到9的
            imagepng($im, $pathname, min((int) (80 / 10), 9));
        } else {
            $fun = 'image' . $type;
            $fun($im, $pathname);
        }
        // echo '[success] ' . $saveName . PHP_EOL;
        return true;
    }

    // public function checkExt($path)
    // {
    //     // PATHINFO_ALL、 PATHINFO_DIRNAME、 PATHINFO_BASENAME、
    //     // PATHINFO_EXTENSION、 PATHINFO_FILENAME
    //     $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    //     if (in_array($ext, $this->extensions)) {
    //         return true;
    //     }
    //     return false;
    // }
}

class WatermarkFacade
{
    public static function __callStatic($method, $args)
    {
        return (new Watermark())->$method(...$args);
    }
}

WatermarkFacade::run();
